﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CZ.PAEZ.SaleManager.ServicePlugIns
{
    [Description("发货汇总汇单保存服务")]
    [HotUpdate]
    public class SaleoutSumSave : AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            foreach (var dataEntity in e.DataEntitys)
            {
                string fid = dataEntity["Id"].ToString();
                // 计算分单号
                string sql = $"exec proc_czty_SSE4Sbmt @FID='{fid}'";
                DBUtils.Execute(Context, sql);
                // 计算发票数量、发货通知单号
                sql = string.Format($"select FInvoice, FBillNo from PAEZ_SaleoutSum where FID={fid}");
                var billinfo = DBUtils.ExecuteDynamicObject(Context, sql).FirstOrDefault();
                if (billinfo == null) continue;
                int len = billinfo["FInvoice"] == null ? 0 : billinfo["FInvoice"].ToString().Split(',').Length;
                sql = string.Format(@"/*dialect*/
declare @max int=(select max(F_PAEZ_FDNo) from PAEZ_SaleoutSumEntry where FID={0});
update s set F_PAEZ_InVoiceQty={1},FMaxSplitNo=@max from PAEZ_SaleoutSum s where FID={0};
update se set F_PAEZ_DelvNotifyNo='{2}-'+convert(varchar(10), F_PAEZ_FDNo), 
    FTotalSplitNo=convert(varchar(10), @max)+'-'+convert(varchar(10), F_PAEZ_FDNo)
from PAEZ_SaleoutSumEntry se where FID={0}",
fid, len, billinfo["FBillNo"]);
                DBUtils.Execute(Context, sql);
            }
        }
    }
}
